<template>
  <div class="">
    <app-head :show="showstate" :title="pagetitle"></app-head>
    <div class="ft14">
      <tab bar-active-color="#23a5a5" defaultColor="#333333" active-color="#23a5a5" :line-width='2' v-model="tabNo">
        <tab-item @on-item-click="tabNo = 0">设备信息</tab-item>
        <tab-item @on-item-click="tabNo = 1">订单信息</tab-item>
      </tab>
    </div>


    <div id="vWrap" v-if="Object.keys(deviceInfo).length > 0 &&tabNo == 0">
      <div class="car-bbinfo-card">
        <div class="bbno lineb">设备编号: {{deviceInfo.Code}}</div>
      </div>

      <div class="car-bbinfo-card">
        <div class="bbmain mb30">
          <p>设备名称:<label>{{deviceInfo.Name}}</label></p>
          <p>型号:<label>{{deviceInfo.Model}}</label></p>
          <p>唯一识别码:<label>{{deviceInfo.Imei}}</label></p>
        </div>
      </div>
    </div>

    <div id="vWrap" v-if="tabNo == 1">
      <div class="car-bbinfo-card">
        <div class="bbno lineb">排车单号: {{$route.query.ATVNo}}</div>
      </div>
    </div>
    
    <scroller class="mainScroller" lock-x scrollbar-y use-pullup :height="scrollerHeight" v-if="datas.length > 0 && tabNo == 1" :pullup-config="ScrollerConfig" ref="Scroller">
      <div>
        <div class="acpt-list">
          <div class="acpt-list-wrap mb30" v-for="(bbitem, index) in datas">
            <div class="acpt-list-head cf">
              <span class="txt f-l">业务单号：{{bbitem.BBillNo}}</span>
            </div>
            <div class="displayflex acpt-list-body lineb">
              <span class="cargo">
                <i class="iconfont icon-cargo"></i>
                <p>{{bbitem.Pkgs}}件</p>
              </span>
              <div class="txt flex1">
                <p class="ft17">{{bbitem.PickContacts}} {{bbitem.PickContactsTel}}</p>
                <p>取货地址：{{bbitem.DepartureCity | city}}{{bbitem.DepartureDistrict | district}}{{bbitem.DepartureAddress}}</p>
                <p>送货地址：{{bbitem.ArrivalCity | city}}{{bbitem.ArrivalDistrict | district}}{{bbitem.ArrivalAddress}}</p>
              </div>
            </div>
            <div class="btn-grp txt-rit">
              <div class="btn ml10 red" @click="removeItem(index, bbitem.MainPoGuid)">移除</div>
            </div>
          </div>
        </div>
      </div>
    </scroller>

    <div class="noDate_page" v-if="(datas.length == 0 && tabNo == 1) || (Object.keys(deviceInfo).length == 0 && tabNo == 0)">
			<div class="noDate_icon"><i class="iconfont icon-null"></i></div>
			{{tabNo == 1?'暂无数据，请扫描单据二维码':'暂无设备，请扫描设备'}}
		</div>

    <div class="displayflex form-btn">
      <div class="flex1" v-if="tabNo == 0" v-on:click="scanQrCode(1)">设备扫码</div>
      <div class="flex1" v-if="tabNo == 1" v-on:click="scanQrCode(2)">订单扫码</div>
      <div class="flex1 cancel" v-on:click="goBind()">确认绑定</div>
    </div>
  </div>
</template>

<script>
import appHead from '@/components/core/header/app_headbar.vue';
import tools from '../../tools/tool.js';
import { mapGetters, mapState } from "vuex";

//851-151,6660-160

export default {
  components:{
    appHead,
  },
  data(){
    return {
      datas:[],
      billnoList:[],
      tabNo:0,
      deviceInfo: {},

      ScrollerConfig: {
        content: "",
        downContent: "",
        height: 0,
        loadingContent: "",
        upContent: ""
      }
    }
  },
  watch: {
    tabNo(n,o){
      if(n === 0){
      } else {
        this.$nextTick(()=> {
          this.$store.dispatch("cfg/setConHeight");
        });
      }
    }
  },
  computed: {
    ...mapState({
      pagetitle: state => state.cfg.appBarTitle,
      showstate: state => state.cfg.showAppBar,
    }),
    ...mapGetters({
      scrollerHeight: "cfg/getConHeight"
    }),
    userinfo(){
      return localStorage.userinfo?JSON.parse(localStorage.userinfo):null
    }
  },
  created(){
  },
  mounted(){
    this.getBindedData();
  },
  methods:{
    getBindedData(){
      let query = {
        AtvGuid: this.$route.query.Guid
      };
      this.Ajax.post("GetBindedData", query).then(resp => {
        if(resp.IsSuccess){
          if(resp.Data){
            this.deviceInfo = resp.Data.Device;
            this.datas = resp.Data.BBList;
            this.datas.forEach(x => {
              this.billnoList.push(x.BBillno);
            })
          }
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    getOrderInfo(bbillno){
      if(!bbillno) {
        this.Toast({
          message: "请扫描正确的订单号",
        });
        return false;
      }
      if(this.billnoList.indexOf(bbillno) > -1) {
        this.Toast({
          message: "此二维码已经扫描过，请换其它二维码扫描",
        });
        return false;
      }

      let query = {
        ATVGuid: this.$route.query.Guid,
        TenantGuid: this.userinfo.TenantGuid,
        BBillno: bbillno.toString()
      }
      this.Ajax.post("GetOrderInfo", query).then(resp => {
        if(resp.IsSuccess){
          this.datas.push(resp.Data);
          this.billnoList.push(bbillno)
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },
    getGPSDeviceInfo(code){
      if(Object.keys(this.deviceInfo).length >0) {
        if(code == this.deviceInfo.Code || code == this.deviceInfo.Imei) {
          this.Toast({
            message: "此二维码为当前选定设备的二维码",
          });
          return false;
        }
      }
      let query = {
        TenantGuid: this.userinfo.TenantGuid,
        Code: code,
        Imei: code,
      }
      this.Ajax.post("GetGPSDeviceInfo", query).then(resp => {
        if(resp.IsSuccess){
          this.deviceInfo = resp.Data;
          this.Toast({
            message: "扫码成功，请扫描需要绑定的订单数据",
            duration: 1500,
          });
          setTimeout(() => {
            this.tabNo = 1;
          },1400)
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    removeItem(i, mainPoGuid) {
      let query = {
        OrderGuid: mainPoGuid,
      };
      this.Ajax.post("RemoveOrderBinding", query).then(resp => {
        if(resp.IsSuccess){
          this.datas.splice(i,1);
          this.billnoList.splice(i,1);
          if(this.datas.length === 0){
            this.resetDeviceState(); //当列表为空时自动还原设备状态
          }
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    resetDeviceState(code){
      let query = {
        UpdateUserId: this.userinfo.StaffID,
        UpdateUserName: this.userinfo.Name,
        TenantGuid: this.userinfo.TenantGuid,
        Guid: this.deviceInfo.Guid,
      };

      if(code) {
        let MainPoGuidList = [];
        if(this.datas.length > 0) {
          this.datas.forEach(x => {
            MainPoGuidList.push(x.MainPoGuid);
          })
          query.MainPoGuidList = MainPoGuidList;
        }
      }

      this.Ajax.post("ResetDeviceState", query).then(resp => {
        if(resp.IsSuccess){
          if(code) {
            this.getGPSDeviceInfo(code);
          }
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    goBind(){
      if(Object.keys(this.deviceInfo).length == 0) {
        this.Toast({
          message: "请扫描设备码",
        });
        return false;
      }

      if(this.datas.length == 0) {
        this.Toast({
          message: "请至少扫描一个订单二维码",
        });
        return false;
      }

      this.$vux.confirm.show({
        title: "请确认",
        content: `将设备${this.deviceInfo.Name}(${this.deviceInfo.Code})绑定至 ${this.datas.length} 笔订单，是否继续？`,
        onCancel : () => {
        },
        onConfirm : () => {
          let query = {
            StaffID: this.userinfo.StaffID,
            UserName: this.userinfo.Name,
            Device: this.deviceInfo,
            BBList: this.datas,
          };
          this.bindingDeviceToOrder(query);
        }
      })
    },
    
    bindingDeviceToOrder(query){
      this.Ajax.post("BindingDeviceToOrder", query).then(resp => {
        if(resp.IsSuccess){
          this.Toast({
            message: "绑定完成",
            duration: 1000,
          });
          setTimeout(() => {
            this.$router.push('/driver/carDraw')
          },900)
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    scanQrCode(type){
      var self = this;
      this.jWeixin.scanQRCode({
        needResult: 1, 
        scanType: ["qrCode", "barCode"],
        success: function(res) {
          var result = res.resultStr;
          if(type == 1) {//851-151,6660-160
            if(result == '556660') result = '556160'
            if(result == '556851') result = '556151'

            if(result == self.deviceInfo.Code) {
              self.Toast({
                message: "此二维码为当前选定设备的二维码",
              });
            } else {
              self.resetDeviceState(result); //扫了新的就清除原有的
            }
          }
          if(type === 2) {
            let temp = result.split(',');
            self.getOrderInfo(temp[0]);
          }
        },
        error: function(res) {
          self.Toast({
            message: res.resultStr,
          });
        }
      });
    },
  }
}
</script>
